package com.tanhua.manager.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.CommentApi;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.api.mongo.VideoApi;
import com.tanhua.domain.db.SensitiveWords;
import com.tanhua.domain.db.UserFreeze;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.manager.api.db.SensitiveWordsApi;
import com.tanhua.manager.api.db.UserFreezeApi;
import com.tanhua.util.RelativeDateFormat;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;

    @Reference
    private VideoApi videoApi;

    public ResponseEntity users(Integer pageNum, Integer pageSize) {

        PageBeanVo pageBeanVo = userInfoApi.findByPage(pageNum, pageSize);
        // 前端工程师在写后台模块的时候，终于发现自己的问题，把age改成了int类型，所以我们这里就不需要封装vo了
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findByUserId(Long userId) {
        UserInfo userInfo = userInfoApi.findByUserId(userId);

        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity messages(Integer pageNum, Integer pageSize, Long userId, Integer state) {
        // 1、调用api查询
        PageBeanVo pageBeanVo = publishApi.findUserByPage(pageNum, pageSize, userId, state);

        // 2、封装publishVo
        List<PublishVo> voList = new ArrayList<>();

        List<Publish> publishList = (List<Publish>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(publishList)) {
            UserInfo userInfo = userInfoApi.findByUserId(userId);
            for (Publish publish : publishList) {
                // userinfo + publish
                PublishVo vo = new PublishVo();
                vo.setUserInfo(userInfo);
                vo.setPublish(publish);
                // 这边有一个坑，需要将时间改为 yyyy-MM-dd HH:mm:ss
                vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()), "yyyy-MM-dd HH:mm:ss"));
                voList.add(vo);
            }
        }

        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findByPublishId(String publishId) {
        // 1、调用api查询
        Publish publish = publishApi.findById(publishId);
        // 2、封装vo
        PublishVo vo = new PublishVo();
        UserInfo userInfo = userInfoApi.findByUserId(publish.getUserId());
        vo.setUserInfo(userInfo);
        vo.setPublish(publish);
        // 这边有一个坑，需要将时间改为 yyyy-MM-dd HH:mm:ss
        vo.setCreateDate(DateUtil.format(new Date(publish.getCreated()), "yyyy-MM-dd HH:mm:ss"));
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity comments(Integer pageNum, Integer pageSize, String publishId) {
        // 1、调用api分页查询
        PageBeanVo pageBeanVo = commentApi.findByPage(pageNum, pageSize, publishId);

        // 2、封装commentVo
        List<CommentVo> voList = new ArrayList<>();
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                CommentVo vo = new CommentVo();
                // 3、封装userInfo
                UserInfo userInfo = userInfoApi.findByUserId(comment.getUserId());
                BeanUtil.copyProperties(userInfo, vo);
                // 4、封装comment
                vo.setContent(comment.getContent()); // 评论内容
                vo.setCreateDate(RelativeDateFormat.format(new Date(comment.getCreated()))); // 评论时间
                vo.setLikeCount(comment.getLikeCount()); // 评论点赞数量
                // 5、将vo添加到list
                voList.add(vo);
            }
        }

        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity videos(Integer pageNum, Integer pageSize, Long userId) {
        // 1、调用api查询
        PageBeanVo pageBeanVo = videoApi.findUserByPage(pageNum, pageSize, userId);

        // 2、封装vo
        List<VideoVo> voList = new ArrayList<>();
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                VideoVo vo = new VideoVo();
                UserInfo userInfo = userInfoApi.findByUserId(video.getUserId());
                BeanUtil.copyProperties(userInfo, vo);
                BeanUtil.copyProperties(video, vo);
                vo.setCover(video.getPicUrl()); // 小视频封面
                vo.setSignature(video.getText()); // 小视频签名
                vo.setId(video.getId().toHexString()); // 小视频id
                voList.add(vo);
            }
        }


        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    @Reference
    private UserFreezeApi userFreezeApi;

    public Integer freeze(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        UserInfo userInfo = userInfoApi.findByUserId(userId);
        userInfo.setUserStatus("2");//设置用户状态初始值2冻结
        userInfoApi.update(userInfo);
        UserFreeze userFreeze = userFreezeApi.findById(userId);
        if (userFreeze == null) {//创建用户冻结事务初始值：0非活跃；1活跃；
            userFreeze = new UserFreeze();
            userFreeze.setId(userId);
            userFreeze.setLogin(0L);
            userFreeze.setCommented(0L);
            userFreeze.setConditions(0L);
            userFreezeApi.saveUser(userFreeze);
        }
        switch (freezingTime) {
            case 1: {//冻结3天
                freezingMethod(userId, freezingRange, reasonsForFreezing, frozenRemarks);
                ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
                ScheduledFuture scheduledFuture = service.schedule(new Runnable() {
                    @Override
                    public void run() {
                        automaticDefrost(userId, freezingRange);
                    }
                }, 3, TimeUnit.DAYS);
                break;
            }
            case 2: {//冻结7天
                freezingMethod(userId, freezingRange, reasonsForFreezing, frozenRemarks);
                ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
                ScheduledFuture scheduledFuture = service.schedule(new Runnable() {
                    @Override
                    public void run() {
                        automaticDefrost(userId, freezingRange);
                    }
                }, 7, TimeUnit.DAYS);
                break;
            }
            case 3: {//永久冻结
                freezingMethod(userId, freezingRange, reasonsForFreezing, frozenRemarks);
                break;
            }
            default:
                break;
        }
        return 2;
    }

    @Reference
    private SensitiveWordsApi sensitiveWordsApi;

    private void freezingMethod(Long userId, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        UserFreeze userFreeze = userFreezeApi.findById(userId);
        if (freezingRange == 1) {//冻结登录
            userFreeze.setLogin(1L);
            userFreezeApi.updateUser(userFreeze);
        } else if (freezingRange == 2) {//冻结发言
            userFreeze.setCommented(1L);
            userFreezeApi.updateUser(userFreeze);
        } else if (freezingRange == 3) {//冻结发布动态
            userFreeze.setConditions(1L);
            userFreezeApi.updateUser(userFreeze);
        }

        SensitiveWords sensitiveWords = new SensitiveWords();
        sensitiveWords.setTypeName(reasonsForFreezing);
        if (!frozenRemarks.isEmpty()) {
            sensitiveWords.setWords(frozenRemarks);//设置冻结原因
            int numWords = frozenRemarks.length();
            sensitiveWords.setWordNum(numWords);//设置冻结备注字数
        } else {
            sensitiveWords.setWords("");//设置冻结原因
            sensitiveWords.setWordNum(0);//设置冻结备注字数
        }
        sensitiveWordsApi.saveSensitiveWords(sensitiveWords);

    }

    private void automaticDefrost(Long userId, Integer freezingRange) {
        UserInfo userInfo = userInfoApi.findByUserId(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        UserFreeze userFreeze = userFreezeApi.findById(userId);
        if (freezingRange == 1) {
            userFreeze.setLogin(0L);
            userFreezeApi.updateUser(userFreeze);
        } else if (freezingRange == 2) {
            userFreeze.setCommented(0L);
            userFreezeApi.updateUser(userFreeze);
        } else if (freezingRange == 3) {
            userFreeze.setConditions(0L);
            userFreezeApi.updateUser(userFreeze);
        }
    }

    public Integer unfreeze(Long userId, String reasonsForThawing) {
        UserInfo userInfo = userInfoApi.findByUserId(userId);
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        UserFreeze userFreeze = userFreezeApi.findById(userId);
        userFreeze.setLogin(0L);
        userFreeze.setCommented(0L);
        userFreeze.setConditions(0L);
        userFreezeApi.updateUser(userFreeze);
        return 1;
    }
}
